<?
class ccdsClassEditor
	extends ccdsBackendPlugin
{
	public  $name = "ccdsClassEditor";

	private $db_fieldtypes = array
	(
		"int" => true,
		"bigint" => true,
		"text" => false,
		"varchar" => true,
		"date" => false,
		"datetime" => false,
		"float" => false
	);


	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function __construct()
	{
		parent::__construct();

		$this->xajax = ccdsXajax::getInstance();

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassOpen", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassTemplatesOpen", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassTemplatesSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorOpen", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorList", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorExtensionList", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorReturnTemplates", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorTemplatesAssignmentSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorTemplatesSave", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassConfig", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassConfigSave", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassConfigAddRow", $this->name );




		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassConfigField", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassConfigFieldSave", $this->name );


		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassParameterConfig", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassParameterConfigSave", $this->name );





		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorTemplatesEdit", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorTemplatesEditSave", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorTemplatesList", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassesOverview", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorExtensionOverview", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorExtensionAdd", $this->name );
		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassAdd", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorTemplatesDelete", $this->name );

		$this->xajax->register( XAJAX_CCDS_FUNCTION, "ClassEditorClassDelete", $this->name );


	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	private function find_key($search_key,&$xml,$path='') {

		if (!is_object($xml) && !is_array($xml)) return false;
		foreach ($xml as $key => $node) {
			if ($search_key == $key) return $node;
				$found = $this->find_key($search_key,$node);
				if (false !== $found) return $found;
			
		}
		return false;
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	
	private function addChilds($key,$value,&$xml) {
		if (!is_object($value)) return;
	
	
		if (0 < count($value->children())) {
			$newchild = $xml->addChild($key,'');
			$childs = $value->children();
			foreach ($value as $k => $child) {
				$this->addChilds($k,$child,$newchild);
			}
		} else {
			
			$xml->addChild($key, (string) $value);
		}
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function convert2XML(&$xml,$class,$classConfig,$array,$type='data') 
	{
		static $insertnodes = array();;
		if ( 'data' == $type) {
			$insert_node = &$xml->data->columns;
		} else {
			$insert_node = &$xml->parameter;
		}

		$i=0;
		
		if (is_array($array['fieldlabel'])) foreach ( $array['fieldlabel'] as $key => $value )
		{
			if ('row_open' == $array['formtype'][$key])
			{
				$insertnodes[]=$insert_node;
				$insert_node = $insert_node->addChild('row','');
				$insert_node->addAttribute('style',$array['fieldlabel'][$key]);
				$insert_node->addAttribute('title',$array['fieldname'][$key]);

			} elseif ('row_close' == $array['formtype'][$key])
			{
				$insert_node = array_pop($insertnodes);
				$insertnodes[] = $insert_node;

			}
			elseif ('column_open' == $array['formtype'][$key])
			{
				$insertnodes[]=$insert_node;
				$insert_node = $insert_node->addChild('column','');

			} elseif ('column_close' == $array['formtype'][$key])
			{
				$insert_node = array_pop($insertnodes);
			}			
			else {
				if ( "" == $array['fieldname'][$key] )
				{
					$fieldname = 'cls_'.strtolower($class['class_name']).'_'.$i;
					$i++;
				} else {
					$fieldname = $array['fieldname'][$key];
				}
					
	
				$child = $insert_node->addChild($fieldname,'');
				$temp = $child;
				$child->addChild('label',$array['fieldlabel'][$key]);
				$child->addChild('length',$array['fieldlength'][$key]);
				$child->addChild('formtype',$array['formtype'][$key]);
				$child->addChild('type',$array['fieldtype'][$key]);
				$child->addChild('oldname',$array['oldfieldname'][$key]);

				$old_child = $this->find_key($fieldname,$classConfig);
				
				if (false != $old_child) 
				{
					foreach ($old_child as $key => $value) 
					{
						if (!isset($child->$key) || 'value' == $key)
						{
							$this->addChilds($key,$value,$child);
						}
					}
				}
			}
			
		}
		
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function simplexml_merge (SimpleXMLElement &$xml1, SimpleXMLElement $xml2,$nodename)
	{
	    // convert SimpleXML objects into DOM ones
	    $dom1 = new DomDocument();
	    $dom2 = new DomDocument();
	    $dom1->loadXML($xml1->asXML());
	    $dom2->loadXML($xml2->asXML());
			
	    // pull all child elements of second XML
	    $xpath = new domXPath($dom2);
	    $xpathQuery = $xpath->query($nodename);
	    for ($i = 0; $i < $xpathQuery->length; $i++)
	    {
	        // and pump them into first one
	        
	        $dom1->documentElement->appendChild(
	            $dom1->importNode($xpathQuery->item($i), true));
	    }
	    $xml1 = simplexml_import_dom($dom1);
	    return $xml1;
	}	
	

	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function createDB($newConfig,$oldConfig,$table,$level=0)
	{
		static $query,$primary,$sep;
		if (!isset($query)) {

			/* that's the way mysql works 
				 CREATE TABLE `usr_web3_1`.`foobar` (
				`id` BIGINT UNSIGNED NOT NULL ,
				`label` VARCHAR( 200 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
				PRIMARY KEY ( `id` )
				) ENGINE = MYISAM 
			*/			
			$query = "CREATE TABLE ".$oldConfig->data->name." (\n";
			$primary = "";
			$sep = "";			
		}
		
		foreach ( $newConfig as $key => $value )
		{
			
			if ('row' == $key || 'column' == $key) {
				
				$this->createDB($value,$oldConfig,$table,$level+1);
				continue;
			}


			// now let's try to generate the query
			
			$fieldname = $key;
			$label = (string) $value->label;
			$length = (string) $value->length;
			$formtype = (string) $value->formtype;
			$type = (string) $value->type;
			$oldname = (string) $value->oldname;

			$mysqltype = $type;

			if ( 'unsigned' == $length )
			{
				if ( 'bigint' == $type )
					$mysqltype .= "(20)";

				if ( 'int' == $type )
					$mysqltype .= "(10)";

				if ( 'varchar' == $type || 'text' == $type || 'mediumtext' == $type )
				{
					//$objResponse->alert( "Felder vom Typ varchar können nicht unsigned sein!" );
					//return $objResponse;
				}
				$mysqltype .= " unsigned ";
			}
			

			if ( 'varchar' == $type && "" == $length )
				$length = 255;

			if ( 0 < $length )
			{
				$mysqltype .= "(".$length.")";
			}
 

			if ( "id" == $label )
				$primary = $key;
			$query .= $sep.$key." ".$mysqltype;

			if ( "varchar" == $type|| "text" == $type || "mediumtext" == $type )
			{
				$query .= " CHARACTER SET utf8 COLLATE utf8_general_ci ";
			}
			$query .= " NOT NULL ";
			$sep = "\n, ";
	 
		}
		
		if (0 == $level) 
		{

			if ( "" != $primary )
				$query .= $sep."PRIMARY KEY (".$primary.")\n";
			$query .= ")";
			$this->ccdSQL->query($query);
		}
		
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function updateDB($newConfig,$oldConfig,$table,$level=0)
	{
		static $changed_names;
		if (!is_array($changed_names)) $changed_names = array();
		
		foreach ( $newConfig as $key => $value )
		{
			
			if ('row' == $key || 'column' == $key) {
				
				$this->updateDB($value,$oldConfig,$table,$level+1);
				continue;
			}
			
			$fieldname = $key;
			$label = (string) $value->label;
			$length = (string) $value->length;
			$formtype = (string) $value->formtype;
			$type = (string) $value->type;
			$oldname = (string) $value->oldname;

			$mysqltype = $type;

			if ( 'unsigned' == $length )
			{
				if ( 'bigint' == $type )
					$mysqltype .= "(20)";

				if ( 'int' == $type )
					$mysqltype .= "(10)";

				if ( 'varchar' == $type || 'text' == $type || 'mediumtext' == $type )
				{
					//$objResponse->alert( "Felder vom Typ varchar können nicht unsigned sein!" );
					//return $objResponse;
				}
				$mysqltype .= " unsigned ";
			}
			

			if ( 'varchar' == $type && "" == $length )
				$length = 255;

			if ( 0 < $length )
			{
				$mysqltype .= "(".$length.")";
			}

	
			/* drop the old name from config */
			//unset($newClassConfig['data']['columns'][$key]['oldname']);
	
			if ( is_array( $table[$fieldname] ) )
			{
				/* merge old and new config to keep (old) additional values alive */
				//if ( is_array($classConfig['data']['columns'][$fieldname] ) )
				//$newClassConfig['data']['columns'][$fieldname] = array_merge( $classConfig['data']['columns'][$fieldname], $newClassConfig['data']['columns'][$fieldname] );
				
				/* let's compare our field config with the mysql field */
				if ( trim($table[$fieldname]['Type']) != trim($mysqltype)  ) {
					/* damn. mismatch! go, fix it */
	
					/* k, that's not a big deal 
					 ALTER TABLE `foobar3` CHANGE `asd` `asd` BIGINT NOT NULL  
					*/
									
					$query = "ALTER TABLE ".$oldConfig->data->name." CHANGE `".$fieldname."` `".$fieldname."` ".$mysqltype;
					if ( "varchar" == $type || "text" == $type || "mediumtext" == $type )
					{
						$query .= " CHARACTER SET utf8 COLLATE utf8_general_ci";
					}
					$query .= " NOT NULL ";
					//print $query."\n";
					$this->ccdSQL->query($query);
						
				}
			}elseif  ($oldname != $fieldname && "" != $oldname )
			{
				/* WTF? the name has changed?!! */
				$query = "ALTER TABLE ".$oldConfig->data->name." CHANGE `".$oldname."` `".$fieldname."` ".$mysqltype;
				if ( "varchar" == $type || "text" == $type || "mediumtext" == $type )
				{
					$query .= " CHARACTER SET utf8 COLLATE utf8_general_ci";
				}
				$query .= " NOT NULL ";
				$this->ccdSQL->query($query);
				$changed_names[] = $oldname;
	
			}				
			else {
				/* Wohoo! let's add a new field */
				/* ALTER TABLE `foo` ADD `bla` VARCHAR( 200 ) NOT NULL ; */
	
				$query = "ALTER TABLE ".$oldConfig->data->name." ADD `".$fieldname."` ".$mysqltype;
				if ( "varchar" == $type || "text" == $type || "mediumtext" == $type )
				{
					$query .= " CHARACTER SET utf8 COLLATE utf8_general_ci";
				}
				$query .= " NOT NULL ";
					//print $query."\n";
				$this->ccdSQL->query($query);
			}
		}
		
		if (0 == $level) 
		{
			foreach ( $table as $key => $value )
				if (!$this->find_key($key,$newConfig) && !in_array($key,$changed_names) ) 
				{
					/* indeed - we'r missing something */
					/* ALTER TABLE `foo` DROP `bla` */
					$query = "ALTER TABLE `".$oldConfig->data->name."` DROP `".$key."`";
					$this->ccdSQL->query($query);
				}
		}
		
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function getNavi($project,&$navi) {

		if (($_SESSION['CMS']['user_level'] >= 1000) OR ($_SESSION['CMS']['user_flags']['project_classes']))
		{

			$classes = array(
				"icon" => $this->config->get("LIBRARY_WEB")."/famfamfam/icons/package.png",
				"id"=>"navi_classes_".$project['project_id'],
				"name" => "Extensions / Klassen",
				"onOpen" => "xajax.request({ccdsfun:'ClassEditorExtensionList',ccdsclass:'ccdsClassEditor'},{parameters:[{project_id:'".$project['project_id']."'}]});",
				"onNameClick" => "xajax.request({ccdsfun:'ClassEditorExtensionOverview',ccdsclass:'ccdsClassEditor'},{parameters:[{project_id:'".$project['project_id']."'}]});",
				"folder" => true
			);
			$navi[0][] = $classes;
						
			$tpls = array(
				"icon" => $this->config->get("LIBRARY_WEB")."/famfamfam/icons/page_white_code.png",
				"id"=>"navi_classes_".$project['project_id'],
				"name" => "Templates",
				"onNameClick" => "xajax.request({ccdsfun:'ClassEditorTemplatesList',ccdsclass:'ccdsClassEditor'},{parameters:[{project_id:'".$project['project_id']."'}]});",
				"folder" => false
			);
			$navi[0][] = $tpls;
		}	
		return false;
	}
	
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorClassAdd ( $aFormValues ) 
	{
		$objResponse = new ccdsResponse();

		if ("" == $aFormValues['class_name']) {
			$objResponse->assign("class_name_error_".$aFormValues['project_id'],"innerHTML","Bitte geben Sie einen Namen fuer die Klasse ein!");
			return $objResponse;
		}

		$query = "SELECT * FROM projects WHERE project_id='".addslashes( $aFormValues['project_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$project = $this->ccdSQL->fetch_assoc($res);

		$query = "SELECT * FROM extensions WHERE ext_id='".addslashes( $aFormValues['ext_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$extension = $this->ccdSQL->fetch_assoc($res);

		 
		
		$dir = strtoupper(preg_replace("/[^a-zA-Z0-9-]/","",$aFormValues['class_name']));

		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id=ext_id WHERE class_name='".$dir."' AND ext_key_project_id='".addslashes( $aFormValues['project_id'] )."'";
		$res = $this->ccdSQL->query($query);
		if ($row = $this->ccdSQL->fetch_assoc($res)) 
		{
			$objResponse->assign("class_name_error_".$aFormValues['project_id'],"innerHTML","Es existiert bereits eine Klasse mit dem Namen '".$dir."'!");
			return $objResponse;
		}


		$class_dir = $this->config->get( 'EXTENSION_DIR' ).$project['project_dir']."/".$extension['ext_dir']."/".$dir;
		
		@mkdir($class_dir,$this->config->get('DIR_CHMOD'),true);


		@mkdir($class_dir."/config",$this->config->get('DIR_CHMOD'),true);
		@mkdir($class_dir."/tpl",$this->config->get('DIR_CHMOD'),true);
		@mkdir($class_dir."/frontend",$this->config->get('DIR_CHMOD'),true);
		@mkdir($class_dir."/lang",$this->config->get('DIR_CHMOD'),true);
		@mkdir($class_dir."/img",$this->config->get('DIR_CHMOD'),true);
		
		$query = "INSERT INTO classes
							(
								class_name,
								class_dir,
								class_key_ext_id
							)
							VALUES
							(
								'".$this->ccdSQL->real_escape_string($dir)."',
								'".$dir."',
								'".$extension['ext_id']."'
							)
		
		";
		$this->ccdSQL->query($query);


   	$this->tools->notify($objResponse,"Die Klasse wurde angelegt.");
		
		$objResponse->loadcommands($this->ClassEditorClassesOverview($aFormValues));
		$objResponse->loadcommands($this->ClassEditorList(array("ext_id" => $extension['ext_id'], "project_id" => $project['project_id'], "update" => true)));


		return $objResponse;			
	}
	
	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	
	/*
		Hinzugefügt von Steffen
		-sauberes Löschen einer Klasse inklusive aller Objekte und Konfigurationen
	*/
	function ClassEditorClassDelete($aFormValues) {
		$objResponse = new ccdsResponse();
		
		$query = "SELECT * FROM projects WHERE project_id='".addslashes( $aFormValues['project_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$project = $this->ccdSQL->fetch_assoc($res);

		$query = "SELECT * FROM extensions WHERE ext_id='".addslashes( $aFormValues['ext_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$extension = $this->ccdSQL->fetch_assoc($res);
		
		$dir = strtoupper(preg_replace("/[^a-zA-Z0-9]/","",$aFormValues['class_name']));
		
		$class_dir = $this->config->get( 'EXTENSION_DIR' ).$project['project_dir']."/".$extension['ext_dir']."/".$dir;
		

		
		$objResponse->loadcommands($this->ClassEditorClassesOverview($aFormValues));
		$objResponse->loadcommands($this->ClassEditorList(array("ext_id" => $extension['ext_id'], "project_id" => $project['project_id'], "update" => true)));
		
		return $objResponse;
	}


	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	
	
	function ClassEditorExtensionAdd ( $aFormValues ) 
	{
		$objResponse = new ccdsResponse();

		if ("" == $aFormValues['ext_name']) {
			$objResponse->assign("ext_name_error_".$aFormValues['project_id'],"innerHTML","Bitte geben Sie einen Namen ein");
			return $objResponse;
		}
	
		$query = "SELECT * FROM extensions WHERE ext_name='".$this->ccdSQL->real_escape_string($aFormValues['ext_name'])."' AND ext_key_project_id='".$aFormValues['project_id']."'";
		$res = $this->ccdSQL->query($query);
		if (0 < $this->ccdSQL->num_rows($res)) {
			$objResponse->assign("ext_name_error_".$aFormValues['project_id'],"innerHTML","Es existiert bereits eine Extension mit diesen Namen");
			return $objResponse;
		}
		$objResponse->clear("ext_name_error_".$aFormValues['project_id'],"innerHTML");

		$query = "SELECT * FROM projects WHERE project_id='".addslashes( $aFormValues['project_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$project = $this->ccdSQL->fetch_assoc($res);
		
		
		$dir = preg_replace("/[^a-zA-Z0-9]/","",$aFormValues['ext_name']);


		
		@mkdir($this->config->get( 'EXTENSION_DIR' ).$project['project_dir']."/".$dir,$this->config->get('DIR_CHMOD'),true);
		
		$query = "INSERT INTO extensions
							(
								ext_name,
								ext_dir,
								ext_key_project_id
							)
							VALUES
							(
								'".$this->ccdSQL->real_escape_string($aFormValues['ext_name'])."',
								'".$dir."',
								'".$aFormValues['project_id']."'
							)
		
		";
		$this->ccdSQL->query($query);
		
		$objResponse->loadcommands($this->ClassEditorExtensionOverview($aFormValues));
		$objResponse->loadcommands($this->ClassEditorExtensionList(array("project_id" => $project['project_id'], "update" => true)));

   	$this->tools->notify($objResponse,"Die Erweiterung wurde angelegt.");

		return $objResponse;			
	}
	
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorExtensionOverview( $aFormValues ) {
		
		$objResponse = new ccdsResponse();

		$extensions = array();

		$query = "SELECT * FROM projects WHERE project_id='".addslashes( $aFormValues['project_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$project = $this->ccdSQL->fetch_assoc($res);
		


		$query = "SELECT * FROM extensions WHERE ext_key_project_id='".addslashes( $aFormValues['project_id'] )."'";
		$res = $this->ccdSQL->query($query);
		while ($ext = $this->ccdSQL->fetch_assoc($res))
		{
			$ext['classes'] = array();
			$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE ext_id='".$ext['ext_id']."'";
			$clsres = $this->ccdSQL->query( $query );
			while ( $class = $this->ccdSQL->fetch_assoc( $clsres ) )
			{
	
				if ( file_exists( $this->config->get( 'EXTENSION_DIR' ).$class['project_dir']."/".$class['ext_dir']."/".$class['class_dir']."/img/icon.png" ) )
				{
					$icon_src = $this->config->get( 'EXTENSION_WEB' ).$class['project_dir']."/".$class['ext_dir']."/".$class['class_dir']."/img/icon.png";
				}
				else
				{
					$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/plugin.png";
				}
				$class['icon'] = $icon_src;
				$ext['classes'][]=$class;
			}				
			$extensions[]=$ext;
		}

		$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/package.png";

		$objResponse->loadcommands( $this->tools->addTabManager( 'topTab', "ClassEditorOverview_".$aFormValues['project_id'],
			"<img src=\"".$icon_src."\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Klassen: ".$project['project_name']."</span>" ) );
		$objResponse->clsTabManager->addPanel( "TabManagerContent_ClassEditorOverview_".$aFormValues['project_id'], array
		(
			"id" => "ClassEditorOverview".$aFormValues['project_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/application.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">&Uuml;bersicht</span>",
			"content" => "<div id='ClassConfig_ClassContainer_".$aFormValues['project_id']."'></div>",
			"closeable" => false
		));
		
		$this->smarty->assign("project",$project);
		$this->smarty->assign("extensions",$extensions);

		$html = $this->smarty->fetch($this->tpl_dir."extensions_overview.tpl");
		
		$objResponse->assign("ClassConfig_ClassContainer_".$aFormValues['project_id'],"innerHTML",$html);
		
		return $objResponse;		
		
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorClassesOverview( $aFormValues = array ())
	{
		
		$objResponse = new ccdsResponse();

		$extensions = array();

		$query = "SELECT * FROM projects WHERE project_id='".addslashes( $aFormValues['project_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$project = $this->ccdSQL->fetch_assoc($res);

		$query = "SELECT * FROM extensions WHERE ext_id='".addslashes( $aFormValues['ext_id'] )."'";
		$res = $this->ccdSQL->query($query);
		$extension = $this->ccdSQL->fetch_assoc($res);

		$classes = array();		
		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE ext_id='".$extension['ext_id']."'";
		$clsres = $this->ccdSQL->query( $query );
		while ( $class = $this->ccdSQL->fetch_assoc( $clsres ) )
		{

			if ( file_exists( $this->config->get( 'EXTENSION_DIR' ).$class['project_dir']."/".$class['ext_dir']."/".$class['class_dir']."/img/icon.png" ) )
			{
				$icon_src = $this->config->get( 'EXTENSION_WEB' ).$class['project_dir']."/".$class['ext_dir']."/".$class['class_dir']."/img/icon.png";
			}
			else
			{
				$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/plugin.png";
			}
			$class['icon'] = $icon_src;
			$classes[]=$class;
		}				

		$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/package.png";

		$objResponse->loadcommands( $this->tools->addTabManager( 'topTab', "ClassEditorOverview_".$aFormValues['project_id'],
			"<img src=\"".$icon_src."\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Klassen: ".$project['project_name']."</span>" ) );
		$objResponse->clsTabManager->addPanel( "TabManagerContent_ClassEditorOverview_".$aFormValues['project_id'], array
		(
			"id" => "ClassEditorOverview".$aFormValues['project_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/application.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">&Uuml;bersicht</span>",
			"content" => "<div id='ClassConfig_ClassContainer_".$aFormValues['project_id']."'></div>",
			"closeable" => false
		));
		
		$this->smarty->assign("project",$project);
		$this->smarty->assign("extension",$extension);
		$this->smarty->assign("classes",$classes);

		$html = $this->smarty->fetch($this->tpl_dir."classes_overview.tpl");
		
		$objResponse->assign("ClassConfig_ClassContainer_".$aFormValues['project_id'],"innerHTML",$html);
		
		return $objResponse;			
	}


	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorTemplatesList($aFormValues) {

		$objResponse = new ccdsResponse();

		$query = "SELECT * FROM projects WHERE project_id='".addslashes($aFormValues['project_id'])."'";
		$res = $this->ccdSQL->query($query);
		$project = $this->ccdSQL->fetch_assoc($res);
		$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/page_white_code.png";

		$objResponse->loadcommands( $this->tools->addTabManager( 'topTab', "Templates_".$aFormValues['project_id'],
			"<img src=\"".$icon_src."\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">".$project['project_name']." Templates</span>" ) );
		$objResponse->clsTabManager->addPanel( "TabManagerContent_Templates_".$aFormValues['project_id'], array
		(
			"id" => "Templates_".$aFormValues['project_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/page_white_code.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">&Uuml;bersicht</span>",
			"content" => "<div id='CTemplates_".$aFormValues['project_id']."'></div>",
			"closeable" => false
		));
		
		
		$query = "SELECT * FROM templates WHERE tpl_key_project_id='".$project['project_id']."' ORDER BY tpl_name";
		$res = $this->ccdSQL->query($query);
		$templates = array();
		while ($row = $this->ccdSQL->fetch_assoc($res)) $templates[] = $row;
		
		$this->smarty->assign("project",$project);
		$this->smarty->assign("templates",$templates);

		$sHtml = $this->smarty->fetch( $this->tpl_dir."/templates.tpl" );
		
		$objResponse->assign("CTemplates_".$aFormValues['project_id'],'innerHTML',$sHtml);

				
		return $objResponse;			
		
	}
	
	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	function ClassEditorTemplatesEdit( $aFormValues )
	{
		$objResponse = new ccdsResponse();
		
		$query = "SELECT * FROM templates WHERE tpl_id='".addslashes($aFormValues['tpl_id'])."'";
		$res = $this->ccdSQL->query($query);
		$tpl = $this->ccdSQL->fetch_assoc($res);
		
		$tpl_file = $this->config->get( 'EXTENSION_DIR' ).$tpl['tpl_dir'].$tpl['tpl_file'];
		@$code = file_get_contents( $tpl_file );
		$tpl['CODE'] = $code;
		$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/page_white_code.png";


		$objResponse->loadcommands( $this->tools->addTabManager( 'topTab', "TemplateEditTab_".$aFormValues['tpl_id'],
			"<img src=\"".$icon_src."\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Template: ".$tpl['tpl_name']."</span>" ) );
		$objResponse->clsTabManager->addPanel( "TabManagerContent_TemplateEditTab_".$aFormValues['tpl_id'], array
		(
			"id" => "TemplateEdit_".$aFormValues['tpl_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/page_white_code.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">&Uuml;bersicht</span>",
			"content" => "<div id='CTemplateEdit_".$aFormValues['tpl_id']."'></div>",
			"closeable" => false
		));

		$this->smarty->assign("tpl",$tpl);

		$sHtml = $this->smarty->fetch( $this->tpl_dir."/template_edit.tpl" );
		$objResponse->assign("CTemplateEdit_".$aFormValues['tpl_id'],'innerHTML',$sHtml);
		
		$objResponse->script('
var editor = CodeMirror.fromTextArea("template_code_'.$tpl['tpl_id'].'", {
  parserfile: "parsexml.js",
  path: "/ccds_library/codemirror/js/",
  stylesheet: "/ccds_library/codemirror/css/xmlcolors.css"
});

		');
		
		
		return $objResponse;
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	function ClassEditorTemplatesEditSave( $aFormValues )
	{
		$objResponse = new ccdsResponse();


		$query = "SELECT * FROM templates WHERE tpl_id='".addslashes($aFormValues['tpl_id'])."'";
		$res = $this->ccdSQL->query($query);
		$tpl = $this->ccdSQL->fetch_assoc($res);
		
		$tpl_file = $this->config->get( 'EXTENSION_DIR' ).$tpl['tpl_dir'].$tpl['tpl_file'];
		file_put_contents( $tpl_file, $aFormValues['template_code'] );

		return $objResponse;
	}	

	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	function ClassEditorTemplatesDelete( $aFormValues )
	{
		$objResponse = new ccdsResponse();

		$query = "DELETE FROM templates WHERE tpl_id='".addslashes($aFormValues['tpl_id'])."'";
		$res = $this->ccdSQL->query($query);

		$query = "DELETE FROM mn_template_class WHERE tpl_class_key_tpl_id='".addslashes($aFormValues['tpl_id'])."'";
		$res = $this->ccdSQL->query($query);
		
		$objResponse->loadcommands($this->ClassEditorTemplatesList($aFormValues));

		return $objResponse;
	}	
	
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorTemplatesAssignmentSave( $aFormValues = array ())
	{
		$objResponse = new ccdsResponse();

		$this->ccdSQL->query( "DELETE FROM mn_template_class WHERE tpl_class_key_class_id='".$aFormValues['class_id']."'" );

		if ( is_array( $aFormValues['templates'] ) )
		{
			foreach ( $aFormValues['templates'] as $tpl )
			{
				if ( $aFormValues['tpl_default'] == $tpl )
				{
					$default = 1;
				}
				else
				{
					$default = 0;
				}
				$query = "INSERT INTO mn_template_class VALUES('".addslashes( $tpl )."','".addslashes( $aFormValues['class_id'] )."','".$default."')";
				$this->ccdSQL->query( $query );
			}
		
		
			if ( 1 == $aFormValues['override_standard_tpl'] && in_array($aFormValues['tpl_default'],$aFormValues['templates'])) 
			{
				$this->ccdSQL->query("
					UPDATE obj_index 
					SET 
						obj_key_tpl_id='".addslashes($aFormValues['tpl_default'])."' WHERE obj_key_class_id='".addslashes($aFormValues['class_id'])."'
				");
			}
		}

		if (is_array($aFormValues['tpl_name']))
		foreach ($aFormValues['tpl_name'] as $tpl_id => $tpl_name) {
			$this->ccdSQL->query("UPDATE templates SET tpl_name='".$this->ccdSQL->real_escape_string($tpl_name)."' WHERE tpl_id='".addslashes($tpl_id)."'");
		}

		

		return $objResponse;
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorTemplatesSave( $aFormValues = array ())
	{
		$objResponse = new ccdsResponse();

		$query = "SELECT * FROM projects WHERE project_id='".addslashes( $aFormValues['project_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$row = $this->ccdSQL->fetch_assoc( $res );
		if ( is_array( $aFormValues['tpl_name'] ) )
		{
			foreach ( $aFormValues['tpl_name'] as $key => $name )
			{

				$aFormValues['tpl_dir'][$key] = preg_replace('|/|','',$aFormValues['tpl_dir'][$key],1);

				$this->ccdSQL->query( "INSERT INTO templates 
												(tpl_name,tpl_file,tpl_dir,tpl_key_project_id) 
												VALUES(
													'".addslashes( $aFormValues['tpl_name'][$key] )."',
													'".addslashes( $aFormValues['tpl_file'][$key] )."',
													'".$root_dir.addslashes( $aFormValues['tpl_dir'][$key] )."',
													'".addslashes( $aFormValues['project_id'] )."'
												)
											" );
			}
		}
		if (is_numeric($aFormValues['class_id']))
		{
			$objResponse->loadcommands( $this->ClassEditorClassTemplates( $aFormValues ) );
		} else {
			$objResponse->loadcommands( $this->ClassEditorTemplatesList( $aFormValues ) );
		}

		return $objResponse;
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorReturnTemplates( $aFormValues = array ())
	{
		$objResponse = new ccdsResponse();
			$this->smarty->assign( "values", $aFormValues['files'] );
			$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_append_tpl.tpl" );
			$objResponse->contextAppend( "container.innerHTML", $sHtml );
//		}
		return $objResponse;
	}




	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorExtensionList( $aFormValues )
	{
		$objResponse = new ccdsResponse();


		$action = true == $aFormValues['update'] ? 'update' : 'add';
 

		$query = "SELECT * FROM extensions LEFT JOIN projects ON project_id = ext_key_project_id WHERE project_id='".addslashes( $aFormValues['project_id'] )."' ORDER by ext_name";
		$res = $this->ccdSQL->query( $query );
		$extensions = array ();

		while ( $row = $this->ccdSQL->fetch_assoc( $res ) )
		{
			$extensions[] = array
			(
				"id" => "navi_ext_".$row['ext_id'],
				"name" => $row['ext_name'],
				"url" => null,
				"icon" => $this->config->get( "LIBRARY_WEB" )."/famfamfam/icons/plugin.png",
				"onOpen" => "xajax.request({ccdsfun:'ClassEditorList',ccdsclass:'ccdsClassEditor'},{parameters:[{project_id:".$aFormValues['project_id'].",ext_id:".$row['ext_id']."}]});",
				"onNameClick" => "xajax.request({ccdsfun:'ClassEditorClassesOverview',ccdsclass:'ccdsClassEditor'},{parameters:[{project_id:".$aFormValues['project_id'].",ext_id:".$row['ext_id']."}]});",
				"folder" => true
			);
		}
		
		if ('update' == $action) {
			$update_obj = array(
				"id" => "navi_classes_".$aFormValues['project_id']
			);		
		} else {
			$update_obj = "navi_classes_".$aFormValues['project_id'];
		}

		$objResponse->script( "$('#CMS_project_tree_".$aFormValues['project_id']."').xTree('".$action."',".json_encode( array
		(
			"parent" => $update_obj,
			"elements" => $extensions
		)).")" );

		$objResponse->script( "$('#CMS_project_tree_".$aFormValues['project_id']."').xTree('open',{id:'navi_classes_".$aFormValues['project_id']."'})" );


		return $objResponse;
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorList( $aFormValues )
	{
		$objResponse = new ccdsResponse();
		
		$action = true == $aFormValues['update'] ? 'update' : 'add';
		
		$action="update";
		$query = "SELECT * FROM classes LEFT JOIN extensions on class_key_ext_id = ext_id LEFT JOIN projects ON project_id = ext_key_project_id WHERE ext_id='".addslashes( $aFormValues['ext_id'] )."' ORDER by ext_name,class_name";
		$res = $this->ccdSQL->query( $query );
		$classes = array ();

		while ( $row = $this->ccdSQL->fetch_assoc( $res ) )
		{
			if ( file_exists( $this->config->get( 'EXTENSION_DIR' ).$row['project_dir']."/".$row['ext_dir']."/".$row['class_dir']."/img/icon.png" ) )
			{
				$row['icon'] = $this->config->get( 'EXTENSION_WEB' ).$row['project_dir']."/".$row['ext_dir']."/".$row['class_dir']."/img/icon.png";
			}
			else
			{
				$row['icon'] = $this->config->get( 'LIBRARY_WEB' )."/famfamfam/icons/plugin.png";
			}
			$classes[] = array
			(
				"id" => "navi_class_".$row['class_id'],
				"name" => $row['class_name'],
				"icon" => $row['icon'],
				"onNameClick" => "xajax.request({ccdsfun:'ClassEditorClassOpen',ccdsclass:'ccdsClassEditor'},{parameters:[{class_id: ".$row['class_id']."}]});"
			);
		}

		if ('update' == $action) 
		{
			$update_obj = array(
				"id" => "navi_ext_".$aFormValues['ext_id']
			);		
		} else {
			$update_obj = "navi_ext_".$aFormValues['ext_id'];
		}

		$objResponse->script( "$('#CMS_project_tree_".$aFormValues['project_id']."').xTree('".$action."',".json_encode( array
		(
			"parent" => $update_obj,
			"elements" => $classes
		)).")" );

		$objResponse->script( "$('#CMS_project_tree_".$aFormValues['project_id']."').xTree('open',{id:'navi_ext_".$aFormValues['ext_id']."'})" );

		return $objResponse;
	}


	/* ---------------------------------------------------------------------------------------------------------------------------------- */

	function ClassEditorClassOpen( $aFormValues )
	{

		$objResponse = new ccdsResponse();

		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		if ( file_exists( $this->config->get( 'EXTENSION_DIR' ).$class['project_dir']."/".$class['ext_dir']."/".$class['class_dir']."/img/icon.png" ) )
		{
			$icon_src = $this->config->get( 'EXTENSION_WEB' ).$class['project_dir']."/".$class['ext_dir']."/".$class['class_dir']."/img/icon.png";
		}
		else
		{
			$icon_src = $this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/plugin.png";
		}

		$objResponse->loadcommands( $this->tools->addTabManager( 'topTab', "Class_".$aFormValues['class_id'],
			"<img src=\"".$icon_src."\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Klasse: ".$class['ext_name']." / ".$class['class_name']."</span>" ) );
		$objResponse->clsTabManager->addPanel( "TabManagerContent_Class_".$aFormValues['class_id'], array
		(
			"id" => "ClassOverview".$aFormValues['class_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/application.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">&Uuml;bersicht</span>",
			"content" => "<div id='ClassConfig_Class_".$aFormValues['class_id']."'></div>",
			"closeable" => false,
			"hide" => true
		));

		$objResponse->clsTabManager->addPanel( "TabManagerContent_Class_".$aFormValues['class_id'], array
		(
			"id" => "ClassTemplates".$aFormValues['class_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/layout_content.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Templates</span>",
			"content" => "<div id='ContentTemplates_Class_".$aFormValues['class_id']."'></div>",
			"closeable" => false,
			"hide" => true
		));
//
		$objResponse->clsTabManager->addPanel( "TabManagerContent_Class_".$aFormValues['class_id'], array
		(
			"id" => "ClassConfig".$aFormValues['class_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/database_gear.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Datenbank </span>",
			"content" => "<div id='ClassConfig_Config_".$aFormValues['class_id']."'></div>",
			"closeable" => false,
			"hide" => false
		));

		$objResponse->clsTabManager->addPanel( "TabManagerContent_Class_".$aFormValues['class_id'], array
		(
			"id" => "ClassParameterConfig".$aFormValues['class_id'],
			"title" => "<img src=\"".$this->config->get( 'LIBRARY_WEB' )."famfamfam/icons/database_gear.png\" border=\"0\" align=\"left\" valign=\"top\" /><span style=\"margin-left:4px;\">Parameter Config </span>",
			"content" => "<div id='ClassConfig_ParameterConfig_".$aFormValues['class_id']."'></div>",
			"closeable" => false,
			"hide" => false
		));


		$objResponse->loadcommands( $this->ClassEditorClassOverview( $aFormValues ) );
		$objResponse->loadcommands( $this->ClassEditorClassTemplates( $aFormValues ) );
		$objResponse->loadcommands( $this->ClassEditorClassConfig( $aFormValues ) );
		$objResponse->loadcommands( $this->ClassEditorClassParameterConfig( $aFormValues ) );

		return $objResponse;
	}


	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassParameterConfig( $aFormValues )
	{

		$formtypes = $this->formFieldHandler->getFieldTypes();



		$stats = array ();
		$mysql_stats = array ();
		$error = "";


		$objResponse = new ccdsResponse();

		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		$this->smarty->assign( "class", $class );

		$ObjectConfig = ccdsObjectConfig::getInstance();
		$classConfig = $ObjectConfig->getClass( $aFormValues['class_id'] );

		if (!is_object($classConfig)) $classConfig = simplexml_load_string('<'.$class['class_name'].'><parameter></parameter></'.$class['class_name'].'>');



		$this->smarty->assign( "db_fieldtypes", $this->db_fieldtypes );
		$this->smarty->assign( "formtypes", $formtypes );
		$id_field = false;


		if (is_object($classConfig))
		{
			$i=0;
			if (!is_object( $classConfig->parameter ) ) 
			{
				$classConfig->addChild('parameter','');
				$fieldname = 'param_'.strtolower($class['class_name']).'_'.$i;
				$newchild = $classConfig->parameter->addchild($fieldname,'');
				$newchild->addchild('fieldlabel','');
				$newchild->addchild('fieldlength','');
				$newchild->addchild('formtype','');
				$newchild->addchild('fieldtype','');
			}
		}
		$this->smarty->assign( "classConfig", $classConfig );

		$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_config_parameter.tpl" );
		$objResponse->assign( "ClassConfig_ParameterConfig_".$aFormValues['class_id'], "innerHTML", $sHtml );

		$objResponse->script( "$('#parameter_config_".$class['class_id']."').tableDnD();" );

		return $objResponse;
	}



	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassParameterConfigSave( $aFormValues )
	{
		$formtypes = $this->formFieldHandler->getFieldTypes();
		

		$stats = array ();
		$mysql_stats = array ();
		$error = "";


		$objResponse = new ccdsResponse();	


		/* first of all, find out if the class exists */
		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		$this->smarty->assign( "class", $class );

		$ObjectConfig = ccdsObjectConfig::getInstance();
		$classConfig = $ObjectConfig->getClass( $aFormValues['class_id'] );
		if (!is_object($classConfig)) $classConfig = simplexml_load_string('<'.$class['class_name'].'><parameter></parameter></'.$class['class_name'].'>');

		$xml = simplexml_load_string('<'.$class['class_name'].'><parameter></parameter></'.$class['class_name'].'>');

		/* write the new config to disk. hopefully it doesn't break anything ;D */

		$this->convert2XML($xml,$class,$classConfig, $aFormValues,'parameter');

		$xml = $this->simplexml_merge( $xml, $classConfig, 'data' );

		$ObjectConfig->saveClass( $aFormValues['class_id'], $xml );

		/* reload interface */
		$objResponse->loadCommands( $this->classEditorClassParameterConfig( array ("class_id" => $aFormValues['class_id'])) );
		return $objResponse;
	}


	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassConfigField( $aFormValues )
	{
		$objResponse = new ccdsResponse();

		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		$this->smarty->assign( "class", $class );		
		
		$query = "SELECT * FROM projects WHERE project_id='".$class['ext_key_project_id']."'";
		$res = $this->ccdSQL->query($query);
		$project = $this->ccdSQL->fetch_assoc($res);
		$this->smarty->assign( "project", $project );		

		$ObjectConfig = ccdsObjectConfig::getInstance();
		$classConfig = $ObjectConfig->getClass( $aFormValues['class_id'] );
		
		if ('data' == $aFormValues['type']) 
		{
			if (is_object($classConfig->data)) 
			{
				if (is_object($classConfig->data->columns)) 
				{
					$field = $this->find_key($aFormValues['fieldname'],$classConfig->data->columns);

					$parser = new ccdsXMLparser($field);
					$config = $parser->getArray();
					$config = $this->formFieldHandler->getFieldConfigArray($config,$class['ext_key_project_id']);
				}
			}
			$target_div =  "ClassConfig_Config_".$aFormValues['class_id'];
		}
		else {
			if (is_array($classConfig['parameter']))
			{

				$field = $this->find_key($aFormValues['fieldname'],$classConfig->parameter);
				$parser = new ccdsXMLparser($field);
				$config = $parser->getArray();
				$config = $this->formFieldHandler->getFieldConfigArray($config,$class['ext_key_project_id']);
			}
			$target_div =  "ClassConfig_ParameterConfig_".$aFormValues['class_id'];
		}
		$this->smarty->assign("type",$aFormValues['type']);
		$this->smarty->assign("class",$class);
		$this->smarty->assign("fieldname",$aFormValues['fieldname']);
		$this->smarty->assign( "classConfig", $classConfig );
		$this->smarty->assign( "config", $config );
		$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_config_field.tpl" );
		$objResponse->assign($target_div, "innerHTML", $sHtml );

		return $objResponse;
	}

	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassConfigFieldSave( $aFormValues )
	{
		$objResponse = new ccdsResponse();

		$ObjectConfig = ccdsObjectConfig::getInstance();
		$classConfig = $ObjectConfig->getClass( $aFormValues['class_id'] );

		if ('data' == $aFormValues['type'])
		{
			if (is_object($classConfig->data)) 
			{
				if (is_object($classConfig->data->columns)) 
				{
					
					if (is_array($aFormValues['formfield'])) 
					{
						
						
	 					foreach ($aFormValues['formfield'] as $fieldname => $values)  					
	 					{

							$field = $this->find_key($fieldname,$classConfig);
							$objResponse->alert(print_r($field,true));
							foreach ($values as $vkey => $value)
							{						
		 						
		 						if (isset($field->$vkey)) {
		 							$field->$vkey =$value;
		 						} else {
		 							$field->addChild($vkey,$value);
		 						}
		 					}
	 					}
						$ObjectConfig->saveClass( $aFormValues['class_id'], $classConfig );
					}
				}
			}
		} elseif ('parameter' == $aFormValues['type'])
		{
			if (is_array($classConfig['parameter'])) 
			{

				if (is_array($aFormValues['formfield'])) 
				{
					
					foreach ($aFormValues['formfield'] as $fieldname => $values)
					{
						$classConfig['parameter'][$fieldname] = array_merge($classConfig['parameter'][$fieldname],$aFormValues['formfield'][$fieldname]);
					}
					$ObjectConfig->saveClass( $aFormValues['class_id'], $classConfig );
				}
			}			
		}
		$objResponse->loadcommands($this->ClassEditorClassConfig($aFormValues));

		return $objResponse;
	}

	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassConfig( $aFormValues )
	{

		$formtypes = $this->formFieldHandler->getFieldTypes();

		$stats = array ();
		$mysql_stats = array ();
		$error = "";


		$objResponse = new ccdsResponse();

		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		$this->smarty->assign( "class", $class );

		$ObjectConfig = ccdsObjectConfig::getInstance();
		$classConfig = $ObjectConfig->getClass( $aFormValues['class_id'] );
		
		
//		$parser = new ccdsXMLparser($classConfig);
//		$classConfig = $parser->getArray();


		$this->smarty->assign( "db_fieldtypes", $this->db_fieldtypes );
		$this->smarty->assign( "formtypes", $formtypes );
		$id_field = false;


		if ( is_object( $classConfig->data ) )
		{
			if ( is_object( $classConfig->data->columns ) ) 
			{

				$cols = $classConfig->data->columns;
				foreach ($cols[0] as $field => $config )
				{
					if ( "id" == $config->label )
						$id_field = $field;
				}
			}
			$this->smarty->assign("import_table",true);
			$this->smarty->assign("tablename",$classConfig['data']['name']);
		} 

		$mysql_conf = $this->config->get('mysql');

		if ( $id_field )
		{
			$query = " SHOW TABLE STATUS FROM `".$mysql_conf['servers']['slave']['db']."` WHERE `name` = '".$classConfig->data->name."' ";
			$res = $this->ccdSQL->query( $query );

			if ( $mysql_stats = $this->ccdSQL->fetch_assoc( $res ) )
			{
				$stats['total_size'] = $this->tools->formatBytes( $mysql_stats['Data_length'] + $mysql_stats['Index_length'] );
				$stats['data_size'] = $this->tools->formatBytes( $mysql_stats['Data_length'] );
				$stats['index_size'] = $this->tools->formatBytes( $mysql_stats['Index_length'] );
				$stats['avg_size_per_row'] = $this->tools->formatBytes( $mysql_stats['Avg_row_length'] );

				unset( $mysql_stats['Data_length'] );
				unset( $mysql_stats['Index_length'] );
				unset( $mysql_stats['Avg_row_length'] );

				$query = "
					SELECT COUNT(*) as anzahl FROM ".$classConfig->data->name."
					STRAIGHT_JOIN obj_versions_index ON (".$id_field." = obj_vers_id)
					STRAIGHT_JOIN obj_index ON (obj_vers_key_obj_id = obj_id)
				";
				if ( $res = $this->ccdSQL->query( $query ) )
				{
					$row = $this->ccdSQL->fetch_assoc( $res );
					$stats['versions'] = $row['anzahl'];

					$query = "
						SELECT COUNT(DISTINCT obj_id) as anzahl FROM ".$classConfig->data->name."
						STRAIGHT_JOIN obj_versions_index ON (".$id_field." = obj_vers_id)
						STRAIGHT_JOIN obj_index ON (obj_vers_key_obj_id = obj_id)
					";
					$res = $this->ccdSQL->query( $query );
					$row = $this->ccdSQL->fetch_assoc( $res );
					$stats['objects'] = $row['anzahl'];
				}else
				{
					$error = $this->smarty->get_config_vars('Classeditor_error_fieldmismatch');
				}
			}else
			{
				$error = $this->smarty->get_config_vars('Classeditor_error_no_table');
				$this->smarty->assign( "tablename", $classConfig['data']['name'] );
				$this->smarty->assign( "new_table", true );
			}
		}elseif ( true == $aFormValues['new_table']  )
		{
			$classConfig = simplexml_load_string(
					'<'.$class['class_name'].'>
					<data>
						<name>neue_Tabelle</name>
						<columns>
							<cls_'.strtolower($class['class_name']).'_id>
								<name></name>
								<label>id</label>
								<type>bigint</type>
								<length>unsigned</length>
								<formtype>hidden</formtype>
							</cls_'.strtolower($class['class_name']).'_id>
							<cls_'.strtolower($class['class_name']).'_>
								<name></name>
								<label></label>
								<length></length>
								<formtype></formtype>
							</cls_'.strtolower($class['class_name']).'_>
						</columns>
					</data>
					</'.$class['class_name'].'>'
			);
		
			$this->smarty->assign( "new_table", true );
		}
		
		$this->smarty->assign( "classConfig", $classConfig );
		$this->smarty->assign( "stats", $stats );
		$this->smarty->assign( "error", $error );
		$this->smarty->assign( "mysql_stats", $mysql_stats );
		$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_config.tpl" );
		$objResponse->assign( "ClassConfig_Config_".$aFormValues['class_id'], "innerHTML", $sHtml );

		$objResponse->script( "$('#table_config_".$class['class_id']."').tableDnD();" );

		return $objResponse;
	}
	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassConfigAddRow( $aFormValues,$new_fieldtype='field' )
	{
		$objResponse = new ccdsResponse();

		if ( isset( $aFormValues['new_table'] ) )
		{
			$this->smarty->assign( "new_table", true );
			$this->smarty->assign( "tablename", $aFormValues['tablename'] );
		}

		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		$this->smarty->assign( "class", $class );

		$ObjectConfig = ccdsObjectConfig::getInstance();
		$classConfig = $ObjectConfig->getClass( $aFormValues['class_id'] );

		$formtypes = $this->formFieldHandler->getFieldTypes();

		
		$this->smarty->assign( "db_fieldtypes", $this->db_fieldtypes );
		$this->smarty->assign( "formtypes", $formtypes );


		$xml = simplexml_load_string('<'.$class['class_name'].'><data><columns></columns></data></'.$class['class_name'].'>');
		
		if ( is_array( $aFormValues['fieldlabel'] ) && !isset($aFormValues['parameter']) )
		{
			$this->convert2XML($xml,$class,$classConfig, $aFormValues);
			$xml->data->addchild('name', (string) $classConfig->data->name);
			$xml->data->addchild('version_control',(int) $classConfig->data->version_control);


			if ('field' == $new_fieldtype) 
			{
				$fieldname = 'cls_'.strtolower($class['class_name']).'_'.$i;
				$newchild = $xml->data->columns->addchild($fieldname,'');
				$newchild->addchild('fieldlabel','');
				$newchild->addchild('fieldlength','');
				$newchild->addchild('formtype','');
				$newchild->addchild('fieldtype','');
				$newchild->addchild('new',1);
				
			}
			if ('row' == $new_fieldtype) {
			
				$newchild = $xml->data->columns->addchild('row','');
	
			}
	
			if ('column' == $new_fieldtype) {
			
				$newchild = $xml->data->columns->addchild('column','');
	
			}
		} else {
			$this->convert2XML($xml,$class,$classConfig, $aFormValues,'parameter');
			$fieldname = 'param_'.strtolower($class['class_name']).'_'.$i;
			$newchild = $xml->parameter->addchild($fieldname,'');
			$newchild->addchild('label','');
			$newchild->addchild('fieldlength','');
			$newchild->addchild('formtype','');
			$newchild->addchild('fieldtype','');			
			$newchild->addchild('new',1);
		}
		
		$classConfig = &$xml;

		$i++;
		$this->smarty->assign( "classConfig", $classConfig );

		$this->smarty->assign( "stats", $stats );
		$this->smarty->assign( "mysql_stats", $mysql_stats );

		if (isset($aFormValues['parameter'])) 
		{
			$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_config_parameter_table.tpl" );
			$objResponse->assign( "parameter_config_container_".$aFormValues['class_id'], "innerHTML", $sHtml );
			$objResponse->script( "$('#parameter_config_".$class['class_id']."').tableDnD();" );
		} else {
			$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_config_table.tpl" );
			$objResponse->assign( "table_config_container_".$aFormValues['class_id'], "innerHTML", $sHtml );
			$objResponse->script( "$('#table_config_".$class['class_id']."').tableDnD();" );
	}

		return $objResponse;
	}


	// -------------------------------------------------------------------------------------------------------------------


	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassConfigSave( $aFormValues )
	{

		$objResponse = new ccdsResponse();
		
		$table = array ();
		$formtypes = $this->formFieldHandler->getFieldTypes();

		
		/* first of all, find out if the class exists */
		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		$this->smarty->assign( "class", $class );

		$ObjectConfig = ccdsObjectConfig::getInstance();
		$classConfig = $ObjectConfig->getClass( $aFormValues['class_id'] );


		$xml = simplexml_load_string('<'.$class['class_name'].'><data><columns></columns></data></'.$class['class_name'].'>');
		if (!is_object($classConfig)) $classConfig = simplexml_load_string('<'.$class['class_name'].'><data><columns></columns></data></'.$class['class_name'].'>');

		$this->convert2XML($xml,$class,$classConfig, $aFormValues);
		
		

		$table = array();
		if ( "" != $classConfig->data->name) 
		{
			$config = ccdsConfig::getInstance();
			$mysql_config = $config->get('mysql');
			$dbname= true == $mysql_config['replication'] ? $mysql_config['servers']['master']['db'] : $mysql_config['servers']['slave']['db'];
			$query = "SELECT *
				FROM information_schema.tables
				WHERE table_schema = '".$dbname."'
				AND table_name = '".$classConfig->data->name."'";
			$res = $this->ccdSQL->query($query);
			if ($row = $this->ccdSQL->fetch_assoc($res)) {
				/* hm'k, seems like there's already an existing table. if so, try go grab the existing columns */
				$query = "SHOW COLUMNS FROM ".$classConfig->data->name;
				$res = @$this->ccdSQL->query( $query );
				
				while ( $field = $this->ccdSQL->fetch_assoc( $res ) )
				{
					$table[$field['Field']] = $field;
				}
			}
		}		
	$changed_names = array();
	$cols = $xml->data->columns;
	$cols = $cols[0];
		
//		/* hm. there's currently no data table in the existing config. Guess we'd better create a new table including config */
		if ( 0 == count($cols) || ( 0 == count($table) && 0 < count($cols)) )
		{
			if ( "" == $aFormValues['tablename'] &&  "" == $classConfig['data']['name'] )
			{
				$objResponse->alert( $this->smarty->get_config_vars('Classeditor_error_tablename') );
				return $objResponse;
			} elseif ( "" == $aFormValues['tablename'] &&  "" != $classConfig['data']['name'] ) {
				$aFormValues['tablename'] = $classConfig['data']['name'];
			}
			if ( 2 > count( $cols ) )
			{
				$objResponse->alert( $this->smarty->get_config_vars('Classeditor_error_2fields') );
				return $objResponse;
			}

			$classConfig->data->name = $aFormValues['tablename'];

			$this->createDB($cols,$classConfig,$table);
			

		} else {

			/* hm'k, seems like there's already an existing table. */
			
			$cols = $xml->data->columns;
			$this->updateDB( $cols[0], $classConfig, $table );
		}

		
		$xml->data->addchild( 'name', (string) $classConfig->data->name );
		$xml->data->addchild( 'version_control', (int) $aFormValues['version_control']);
	
		if (is_object($classConfig))
		$xml = $this->simplexml_merge( $xml, $classConfig, 'parameter' );

		
		/* write the new config to disk. hopefully it doesn't break anything ;D */
 		$ObjectConfig->saveClass( $aFormValues['class_id'], $xml );


   	$this->tools->notify( $objResponse, $this->smarty->get_config_vars('Classeditor_config_saved') );

		/* reload interface */
		$objResponse->loadCommands( $this->classEditorClassConfig( array ("class_id" => $aFormValues['class_id'] ) ) );
		return $objResponse;
	}

	// -------------------------------------------------------------------------------------------------------------------

	function ClassEditorClassOverview( $aFormValues )
	{
		$objResponse = new ccdsResponse();

		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );

		$this->smarty->assign( "class", $class );

		$permissions = $this->tools->getPermissionsClass2Class( $aFormValues['class_id'] );
		$this->smarty->assign( "permissions", $permissions );
		$classes = array ();
		$query = "SELECT * FROM classes
	           LEFT JOIN extensions ON
	           class_key_ext_id = ext_id
	           WHERE ext_key_project_id='".$class['project_id']."'
	
	           ORDER BY class_name";
		$res = $this->ccdSQL->query( $query );

		while ( $row = $this->ccdSQL->fetch_assoc( $res ) )
			$classes[] = $row;

		$this->smarty->assign( "classes", $classes );
		$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_edit.tpl" );

		$objResponse->assign( "ClassConfig_Class_".$aFormValues['class_id'], "innerHTML", $sHtml );

		return $objResponse;
	}

	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	function ClassEditorClassSave( $aFormValues )
	{

		$objResponse = new ccdsResponse();

		$this->ccdSQL->query( "DELETE FROM permissions_class_2_class WHERE class_2_class_node_id='".$aFormValues['class_id']."' " );

		if ( is_array( $aFormValues['classes'] ) )
			foreach ( $aFormValues['classes'] as $class_id => $class )
			{
				if ( $class['allow'] == 1 )
				{
					if ( "" == $class['visible'] )
						$class['visible'] = 0;
					$this->ccdSQL->query( "INSERT INTO permissions_class_2_class VALUES ('".addslashes( $aFormValues['class_id'] )."','".addslashes( $class_id )."','".addslashes( $class['visible'] )."')" );
				}
			}

   	$this->tools->notify($objResponse,"Die Einstellungen wurden gespeichert.");

		$objResponse->script( "Windows.close('ClassEditorWindow');" );
		return $objResponse;
	}
	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	function ClassEditorClassTemplates( $aFormValues )
	{

		$objResponse = new ccdsResponse();
		$query = "SELECT * FROM classes LEFT JOIN extensions ON class_key_ext_id = ext_id LEFT JOIN projects ON ext_key_project_id = project_id WHERE class_id='".addslashes( $aFormValues['class_id'] )."' LIMIT 1";
		$res = $this->ccdSQL->query( $query );
		$class = $this->ccdSQL->fetch_assoc( $res );
		$this->smarty->assign( "class", $class );
		$templates = array ();
		$query = "SELECT * FROM templates LEFT JOIN mn_template_class ON tpl_class_key_tpl_id = tpl_id WHERE tpl_key_project_id='".$class['project_id']."' ORDER BY tpl_name";
		$res = $this->ccdSQL->query( $query );

		while ( $row = $this->ccdSQL->fetch_assoc( $res ) )
		{
			$templates[] = $row;
		}

		$this->smarty->assign( "class", $class );
		$this->smarty->assign( "project_id", $class['project_id'] );
		$this->smarty->assign( "templates", $templates );

		$sHtml = $this->smarty->fetch( $this->tpl_dir."/class_templates.tpl" );
		$objResponse->assign( "ContentTemplates_Class_".$aFormValues['class_id'], "innerHTML", $sHtml );

		return $objResponse;
	}


	/* ---------------------------------------------------------------------------------------------------------------------------------- */
	function ClassEditorClassTemplatesSave( $aFormValues )
	{

		$objResponse = new ccdsResponse();

		$this->ccdSQL->query( "UPDATE templates SET tpl_key_class_id='0' WHERE tpl_key_class_id='".$aFormValues['class_id']."'" );

		if ( is_array( $aFormValues['fields'] ) )
			foreach ( $aFormValues['fields'] as $field )
			{

				$tpl_id = str_replace( "tpl_", "", $field );

				$this->ccdSQL->query( "UPDATE templates SET tpl_key_class_id='".$aFormValues['class_id']."' WHERE tpl_id='".$tpl_id."'" );
			}

		$this->ccdSQL->query( "UPDATE templates SET tpl_default='0' WHERE tpl_key_class_id='".$aFormValues['class_id']."'" );

		if ( $aFormValues['defaultTpl'] != "undefined" )
		{
			$this->ccdSQL->query( "UPDATE templates SET tpl_default='1' WHERE tpl_id='".$aFormValues['defaultTpl']."'" );
		}

		$objResponse->script( "Windows.close('ClassEditorTemplateWindow');" );
		$objResponse->loadcommands( $this->ClassEditorOpen( array ("project_id" => $aFormValues['project_id'])) );

		return $objResponse;
	}
/* ---------------------------------------------------------------------------------------------------------------------------------- */


}


$ccdsModuleManager = ccdsModuleManager::getInstance();
$ccdsModuleManager->register('project_navi','ccdsClassEditor','getNavi');
?>